package com.qfoud.edu.shiro.framwork.slot.impl;

import com.qfoud.edu.shiro.framwork.auth.AuthticationInfo;
import com.qfoud.edu.shiro.framwork.exception.ShiroException;
import com.qfoud.edu.shiro.framwork.manager.AuthticationManager;
import com.qfoud.edu.shiro.framwork.manager.impl.AuthticationManagerImpl;
import com.qfoud.edu.shiro.framwork.slot.base.BaseSlot;
import com.qfoud.edu.shiro.framwork.utils.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;

/**
 * @author xiaobobo
 * @title: AuthticationSlot
 * @projectName cd-java-2303-project-parent
 * @description: TODO
 * @date 2023/5/15  15:05
 */
public class AuthticationSlot implements BaseSlot {

    private AuthticationManager authticationManager=new AuthticationManagerImpl();

    private String loginUrl;

    public AuthticationSlot(String loginUrl){
          this.loginUrl=loginUrl;
    }

    @Override
    public void dealRequestAndResponse(ServletRequest request, ServletResponse response) throws UnsupportedEncodingException {

        System.out.println("登陆的slot执行了....");
        //在这里首先要判断这个地址是不是登陆?
        HttpServletRequest req= (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        if(StringUtils.equals(loginUrl,requestURI)){
            //首先要取出我们的数据
            AuthticationInfo authticationInfo=getAuthticationInfo(request);
            try {
                authticationManager.auth(authticationInfo,request,response);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 取出用户信息
     * 登陆只能使用post方式去登陆
     * @param servletRequest
     * @return
     */
    private AuthticationInfo getAuthticationInfo(ServletRequest servletRequest) throws UnsupportedEncodingException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("UTF-8");
        String method = request.getMethod();
        AuthticationInfo authticationInfo=new AuthticationInfo();
        if("POST".equalsIgnoreCase(method)){
            //说明前端是POST方法满足我们的条件
            //取出用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //接下来将这两个信息封装到AuthticationInfo中去
            authticationInfo.setUsername(username);
            authticationInfo.setPassword(password);
        }else{
            throw new ShiroException("请求方法不是POST登陆不支持");
        }
        return authticationInfo;
    }
}
